<template>
  <div>
    <a-dropdown>
      <div class="header-avatar" style="cursor: pointer">
        <img
          style="
            width: 32px;
            height: 32px;
            border-radius: 50%;
            margin-right: 10px;
            align-self: center;
          "
          v-real-img="user.headImage"
        />
        <span class="name">{{ user.name }}</span>
      </div>
      <a-menu :class="['avatar-menu']" slot="overlay">
        <a-menu-item @click="editSecret">
          <a-icon type="key" />
          <span>修改密码</span>
        </a-menu-item>
        <a-menu-item @click="editAvatar">
          <a-icon type="user" />
          <span>修改头像</span>
        </a-menu-item>
        <a-menu-divider />
        <a-menu-item @click="logout">
          <a-icon style="margin-right: 8px" type="poweroff" />
          <span>退出登录</span>
        </a-menu-item>
      </a-menu>
    </a-dropdown>
    <changepwd
      ref="changepwd"
      v-if="changepwd.visible"
      :visible.sync="changepwd.visible"
      :title="changepwd.title"
    ></changepwd>
    <avatar
      ref="avatar"
      v-if="avatar.visible"
      :visible.sync="avatar.visible"
      :headImage="headImage"
      :title="avatar.title"
      @ok="avatarOk"
    ></avatar>
  </div>
</template>

<script>
import { mapMutations, mapGetters } from "vuex";
import changepwd from "@/pages/system/user/changepwd";
import avatar from "@/pages/system/user/avatar";
import { logout } from "@/services/account/login";

export default {
  components: {
    changepwd,
    avatar,
  },
  name: "HeaderAvatar",
  computed: {
    ...mapGetters("account", ["user"]),
  },
  data() {
    return {
      changepwd: {
        visible: false,
        title: "",
      },
      avatar: {
        visible: false,
        title: "",
      },
      headImage: null,
    };
  },
  created() {
    this.userName = this.user.name;
  },
  methods: {
    ...mapMutations("account", ["setUser"]),
    logout() {
      logout();
      this.$router.push("/login");
    },

    /**
     * 重置密码
     */
    editSecret() {
      this.changepwd.visible = true;
      this.changepwd.title = "修改密码-" + this.userName;
    },

    editAvatar() {
      this.headImage = !this.user.headImage
        ? require("@/assets/avatar.jpg")
        : this.user.headImage;
      this.avatar.visible = true;
      this.avatar.title = "修改头像-" + this.userName;
    },

    /**
     * 修改头像
     * @param {*} data
     */
    avatarOk(data) {
      console.log(data);
      this.user.headImage = data;
      this.setUser(this.user);
    },
  },
};
</script>

<style lang="less">
.header-avatar {
  display: inline-flex;
  .avatar,
  .name {
    align-self: center;
  }
  .avatar {
    margin-right: 8px;
  }
  .name {
    font-weight: 500;
  }
}
.avatar-menu {
  width: 150px;
}
</style>
